import React from "react";
const CountDown = (props:any) => {
    const { initialSeconds, buttonTextBefore, SendEmail } = props;
    const [secondsLeft, setSecondsLeft] = React.useState(initialSeconds);
    const [isCountingDown, setIsCountingDown] = React.useState(false);

    React.useEffect(() => 
    {
        let timer:any;
        if (isCountingDown && secondsLeft > 0) {
            timer = setTimeout(() => {
                setSecondsLeft((prevSeconds: number) => prevSeconds - 1);
            }, 1000);
        } else if (secondsLeft === 0) {
            // 倒计时结束，并重置相关状态
            setIsCountingDown(false);
            setSecondsLeft(initialSeconds);
            clearTimeout(timer);
        }
        return () => clearTimeout(timer);
    }, [isCountingDown, secondsLeft]);

    const HandleButtonClick = () => 
    {
        // 发送验证码
        SendEmail()
        setIsCountingDown(true);
    };

    return (
        <React.UI.Button
            size={isCountingDown?'mini' :'small'}
            color="primary"
            disabled={isCountingDown}
            onClick={HandleButtonClick}
        >
            {isCountingDown? `${secondsLeft}秒` : buttonTextBefore}
        </React.UI.Button>
    );
};

export default CountDown;